import { unref, isRef, watch, ref, h, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { RadioGroup, Radio, Input } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { useModal } from '/@/components/Modal';
import { useDrawer } from '/@/components/Drawer';
import { useListPage } from '/@/hooks/system/useListPage';
import { buildUUID } from '/@/utils/uuid';
import { isArray } from '/@/utils/is';
import Clipboard from 'clipboard';
import { useDesign } from '/@/hooks/web/useDesign';
import intro from 'intro.js';
import 'intro.js/minified/introjs.min.css';

import { list, doCopyOnlineView, doBatchRemove, doBatchDelete, doDatabaseSync, doCopyTable } from '../cgform.api';

enum CgformPageType {
  normal = 0,
  copy = 1,
}

const COPY_CLASS = 'copy-this-text';
const CLIPBOARD_TEXT = 'data-clipboard-text';
function useCopyModal() {
  return { createCopyModal };
}
const { createMessage, createConfirm } = useMessage();
function createCopyModal(options) {
  let _a, _b, _c, _d, _e;
  const url = unref(options.copyText);
  const insertMenuSql = ` INSERT INTO sys_permission(id,system_id,parent_id,name,url,component,is_route,component_name,request_method,redirect,menu_type,perms,perms_type,sort_no,always_show,icon,is_leaf,keep_alive,hidden,hide_tab,description,is_del,is_rule,status,internal_or_external,tenant_id,) 
  VALUES ('${buildUUID()}', '', '', '${
    options.copyTitle
  }', '${url}', '${url}', 0, '', NULL, NULL, 0, NULL, '0', 1.00, 0, '', 1, 0, 0, 0, NULL, 0, 0, NULL, 0, NULL)`;

  const modal = createConfirm(
    Object.assign({}, options, {
      iconType: (_a = options.iconType) != null ? _a : 'info',
      width: (_b = options.width) != null ? _b : 500,
      title: (_c = options.title) != null ? _c : '复制',
      closable: true,
      maskClosable: (_d = options.maskClosable) != null ? _d : true,
      cancelText: '复制SQL',
      okText: (_e = options.okText) != null ? _e : '复制URL',
      cancelButtonProps: {
        class: 'copy-this-sql',
        'data-clipboard-text': insertMenuSql,
      },
      okButtonProps: Object.assign({}, options.okButtonProps, {
        class: COPY_CLASS,
        [CLIPBOARD_TEXT]: url,
      }),
      onOk() {
        return new Promise((resolve) => {
          const clipboard = new Clipboard('.' + COPY_CLASS);
          clipboard.on('success', () => {
            clipboard.destroy();
            createMessage.success('复制URL成功');
            resolve();
          });
          clipboard.on('error', () => {
            createMessage.error('该浏览器不支持自动复制');
            clipboard.destroy();
            resolve();
          });
        });
      },
      onCancel() {
        return new Promise((resolve) => {
          const clipboard = new Clipboard('.copy-this-sql');
          clipboard.on('success', () => {
            clipboard.destroy();
            createMessage.success('复制插入菜单SQL成功');
            resolve();
          });
          clipboard.on('error', () => {
            createMessage.error('该浏览器不支持自动复制');
            clipboard.destroy();
            resolve();
          });
        });
      },
    })
  );

  if (isRef(options.copyText)) {
    watch(options.copyText, (copyText) => {
      modal.update({
        okButtonProps: Object.assign({}, options.okButtonProps, {
          class: COPY_CLASS,
          [CLIPBOARD_TEXT]: copyText,
        }),
      });
    });
  }
  return modal;
}

function useCgformIntro() {
  const { prefixVar } = useDesign('');
  const newAddBtn = ref(`${prefixVar}-online-newAddBtn`);
  const customBtn = ref(`${prefixVar}-online-customBtn`);
  const enhanceJsBtn = ref(`${prefixVar}-online-enhanceJsBtn`);
  const enhanceSqlBtn = ref(`${prefixVar}-online-enhanceSqlBtn`);
  const enhanceJavaBtn = ref(`${prefixVar}-online-enhanceJavaBtn`);
  const exportDbBtn = ref(`${prefixVar}-online-exportDbBtn`);
  const codeGeneratorBtn = ref(`${prefixVar}-online-codeGenerator`);
  const guide = `${prefixVar}-online-guide`;

  function handleStartIntro() {
    intro()
      .setOptions({
        nextLabel: '下一步',
        prevLabel: '上一步',
        //skipLabel: '跳过',
        doneLabel: '完成',
        steps: [
          {
            title: '第一步',
            element: document.querySelector(`.${newAddBtn.value}`),
            intro: '点击<strong>新增</strong>按钮，新建一个表。',
          },
          {
            title: '第二步',
            intro: '在列表中找到刚才新建数据，在操作列点击<strong>"更多"</strong>，选择<strong>"同步数据库"</strong>。',
          },
          {
            title: '第三步',
            intro: '在列表中找到刚才新建数据，在操作列点击<strong>"更多"</strong>，选择<strong>"功能测试"</strong>。',
          },
          {
            title: '代码生成',
            element: document.querySelector(`.${codeGeneratorBtn.value}`),
            intro: '选中一条记录，通过代码生成可将已配置好的表单，一键生成前后端代码，复杂需求可在此基础上进行二次开发。',
          },
          {
            title: '自定义按钮',
            element: document.querySelector(`.${customBtn.value}`),
            intro: '选中一条记录，点击自定义按钮，配置按钮相关信息即可在当前记录的<strong>"功能测试"</strong>页面新增一个按钮',
          },
          {
            title: 'JS强增',
            element: document.querySelector(`.${enhanceJsBtn.value}`),
            intro: '选中一条记录，通过js增强可为<strong>"自定义按钮"</strong>添加不同操作，可操作列表和表单数据等，也可以添加表单前置事件。',
          },
          {
            title: 'SQL增强',
            element: document.querySelector(`.${enhanceSqlBtn.value}`),
            intro: '选中一条记录，通过增强SQL，可以关联修改业务数据。',
          },
          {
            title: 'java增强',
            element: document.querySelector(`.${enhanceJavaBtn.value}`),
            intro: '选中一条记录，通过Java增强可在表单的增加、修改、和删除数据时实现额外的功能，类似spring中的AOP切面编程。',
          },
          {
            title: '导入数据库表',
            element: document.querySelector(`.${exportDbBtn.value}`),
            intro: '可将已有数据库中的表，直接导入生成表单。',
          },
        ],
      })
      .start();
  }

  return (
    onMounted(() => {
      localStorage.getItem(guide) ||
        setTimeout(() => {
          handleStartIntro();
          localStorage.setItem(guide, '1');
        }, 2000);
    }),
    { newAddBtn, customBtn, enhanceJsBtn, enhanceSqlBtn, exportDbBtn, enhanceJavaBtn, codeGeneratorBtn }
  );
}

function useCgformList(options) {
  const isNormalPage = options.pageType === CgformPageType.normal;
  const router = useRouter();
  const pageContext = useListPage({
    designScope: options.designScope,
    tableProps: {
      api: list,
      columns: options.columns,
      formConfig: {
        schemas: options.formSchemas,
      },
      beforeFetch: (params) => {
        const copyType = isNormalPage ? 0 : 1;
        const physicId = isNormalPage ? void 0 : router.currentRoute.value.params.code;
        if (isArray(params.tableType_MultiString)) {
          params.tableType_MultiString = params.tableType_MultiString.join(',');
        }
        return Object.assign(params, { copyType, physicId });
      },
    },
  });
  const { tableContext, createMessage: $message, createConfirm: $confirm } = pageContext;
  const [, { reload, setLoading }, { selectedRowKeys, selectedRows }] = tableContext;
  const [registerCgformModal, cgformModal] = useModal();
  const [registerDbToOnlineModal, dbToOnlineModal] = useModal();
  const [registerCodeGeneratorModal, codeGeneratorModal] = useModal();
  const [registerCustomButtonModal, customButtonModal] = useModal();
  const [registerEnhanceJsModal, enhanceJsModal] = useModal();
  const [registerEnhanceSqlModal, enhanceSqlModal] = useModal();
  const [registerEnhanceJavaModal, enhanceJavaModal] = useModal();
  const [registerAuthManagerDrawer, authManagerDrawer] = useDrawer();
  const [registerAuthSetterModal, authSetterModal] = useModal();
  function onAdd() {
    cgformModal.openModal(true, { isUpdate: false });
  }
  function onEdit(record) {
    cgformModal.openModal(true, { isUpdate: true, record });
  }
  function onDeleteBatch() {
    const idList = selectedRowKeys.value;
    if (idList.length <= 0) {
      $message.warning('请先选择一条记录！');
      return;
    }
    $confirm({
      title: '删除',
      content: '<p>移除只会删除表单配置；<br>删除则会删除对应的数据库表以及子表且不能恢复。<br>请确认您的操作…</p>',
      iconType: 'warning',
      closable: true,
      okText: '移除',
      cancelText: '删除',
      cancelButtonProps: { danger: true },
      onOk: async () => {
        executeDelete(doBatchRemove, idList, true);
      },
      onCancel(event) {
        if (!(event == null ? void 0 : event.triggerCancel)) {
          return executeDelete(doBatchDelete, idList, true);
        }
        return Promise.resolve();
      },
    });
  }
  async function executeDelete(fn, idList, clearSelected = false) {
    try {
      setLoading(true);
      const res = await fn(idList);
      reload();
      if (clearSelected) {
        selectedRowKeys.value = [];
      }
      return res;
    } finally {
      setLoading(false);
    }
  }
  function onShowCustomButton() {
    getSelectedRows(([row]) => customButtonModal.openModal(true, { row }));
  }
  function onShowEnhanceJs() {
    getSelectedRows(([row]) => enhanceJsModal.openModal(true, { row }));
  }
  function onShowEnhanceSql() {
    getSelectedRows(([row]) => enhanceSqlModal.openModal(true, { row }));
  }
  function onShowEnhanceJava() {
    getSelectedRows(([row]) => enhanceJavaModal.openModal(true, { row }));
  }
  function onImportDbTable() {
    dbToOnlineModal.openModal(true, {});
  }
  function getSelectedRows(fn, min = 1, max = 1) {
    if (selectedRows.value.length < min) {
      $message.warning(`请先至少选中 ${min} 条记录`);
    } else if (selectedRows.value.length > max) {
      $message.warning(`最多只能选中 ${min} 条记录`);
    } else {
      fn(selectedRows.value);
    }
  }
  function onGenerateCode() {
    if (selectedRows.value.length === 0) {
      $message.warning('请先选中一条记录');
    } else if (selectedRows.value.length > 1) {
      $message.warning('代码生成只能选中一条记录');
    } else {
      const row = selectedRows.value[0];
      if (!row) {
        $message.warning('请选中当前页的数据！');
      } else if (row.isDbSynch != 'Y') {
        $message.warning('请先同步数据库！');
      } else if (row.tableType == 3) {
        $message.warning('请选中该表对应的主表');
      } else {
        codeGeneratorModal.openModal(true, { code: row.id });
      }
    }
  }
  function onGoToTest(record) {
    console.log(record);
    if (record.isTree == 'Y') {
      router.push({ path: '/online/cgformTreeList/' + record.id });
    } else {
      router.push({ path: '/online/cgformList/' + record.id });
    }
  }
  function onSyncDatabase(record) {
    const syncMethod = ref('normal');
    const disabled = ref(false);
    const modalFunc = $confirm({
      iconType: 'info',
      title: '同步数据库',
      content: () =>
        h(
          'div',
          {
            style: 'margin: 20px 0;',
          },
          h(
            RadioGroup,
            {
              value: syncMethod.value,
              disabled: disabled.value,
              'onUpdate:value': (v) => (syncMethod.value = v),
            },
            () => [h(Radio, { value: 'normal' }, () => '普通同步（保留表数据）'), h(Radio, { value: 'force' }, () => '强制同步（删除表，重新生成）')]
          )
        ),
      maskClosable: true,
      okText: '开始同步',
      onOk: async () => {
        disabled.value = true;
        modalFunc.update({
          maskClosable: false,
          keyboard: false,
          okText: '同步中…',
          okButtonProps: { loading: disabled.value },
          cancelButtonProps: { disabled: disabled.value },
        });
        try {
          await doDatabaseSync(record.id, syncMethod.value);
        } catch (e) {
          $message.warn(e.message || e);
        } finally {
          reload();
        }
      },
    });
  }
  const { createCopyModal } = useCopyModal();
  function onShowOnlineUrl(record) {
    let onlineUrl;
    if (record.themeTemplate === 'erp') {
      onlineUrl = `/online/cgformErpList/${record.id}`;
    } else if (record.themeTemplate === 'innerTable') {
      onlineUrl = `/online/cgformInnerTableList/${record.id}`;
    } else if (record.themeTemplate === 'tab') {
      onlineUrl = `/online/cgformTabList/${record.id}`;
    } else if (record.isTree == 'Y') {
      onlineUrl = `/online/cgformTreeList/${record.id}`;
    } else {
      onlineUrl = `/online/cgformList/${record.id}`;
    }
    createCopyModal({
      title: `菜单链接【${record.tableTxt}】`,
      content: onlineUrl,
      copyText: onlineUrl,
    });
  }
  function onCopyTable(record) {
    const tableName = ref(record.tableName + '_copy');
    $confirm({
      title: '复制表',
      content: () =>
        h(
          'div',
          {
            style: 'margin: 20px 0;',
          },
          [
            '请输入新表名：',
            h(Input, {
              value: tableName.value,
              'onUpdate:value': (v) => (tableName.value = v),
            }),
          ]
        ),
      iconType: 'info',
      closable: true,
      okText: '复制',
      onOk() {
        if (!tableName.value) {
          $message.warning('请输入新表名');
        } else if (tableName.value === record.tableName) {
          $message.warning('新表名和旧表名不能一致');
        } else {
          doCopyTable(record.id, tableName.value).then(reload);
        }
      },
    });
  }
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: () => onEdit(record),
      },
    ];
  }
  function getDropDownAction(record) {
    return [
      {
        label: '同步数据库',
        onClick: () => onSyncDatabase(record),
        ifShow: () => isNormalPage && record.isDbSynch != 'Y',
      },
      {
        label: '功能测试',
        class: ['low-app-hide'],
        onClick: () => onGoToTest(record),
        ifShow: () => (isNormalPage ? record.isDbSynch == 'Y' && record.tableType !== 3 : true),
      },
      {
        label: '配置地址',
        class: ['low-app-hide'],
        onClick: () => onShowOnlineUrl(record),
        ifShow: () => (isNormalPage ? record.isDbSynch == 'Y' && record.tableType !== 3 : true),
      },
      {
        label: '权限控制',
        onClick: () => authManagerDrawer.openDrawer(true, { cgformId: record.id }),
      },
      {
        label: '角色授权',
        onClick: () => authSetterModal.openModal(true, { cgformId: record.id }),
      },
      {
        label: '视图管理',
        class: ['low-app-hide'],
        onClick: () => router.push(`/online/copyform/${record.id}`),
        ifShow: () => isNormalPage && record.hascopy == 1,
      },
      {
        label: '生成视图',
        class: ['low-app-hide'],
        popConfirm: {
          title: '确定生成视图吗？',
          placement: 'left',
          confirm: () => {
            setLoading(true);
            doCopyOnlineView(record.id)
              .then(() => {
                $message.success('已成功生成视图');
              })
              .finally(() => {
                setLoading(false);
                reload();
              });
          },
        },
        ifShow: () => isNormalPage,
      },
      {
        label: '复制表',
        onClick: () => onCopyTable(record),
        ifShow: () => isNormalPage,
      },
      {
        label: '移除',
        popConfirm: {
          title: '确定移除吗？',
          placement: 'left',
          confirm: () => executeDelete(doBatchRemove, [record.id]),
        },
      },
      {
        label: '删除',
        popConfirm: {
          title: '确定删除吗？',
          placement: 'left',
          confirm: () => executeDelete(doBatchDelete, [record.id]),
        },
        ifShow: () => isNormalPage,
      },
    ];
  }
  return {
    router,
    pageContext,
    onAdd,
    onDeleteBatch,
    onImportDbTable,
    onGenerateCode,
    onShowCustomButton,
    onShowEnhanceJs,
    onShowEnhanceSql,
    onShowEnhanceJava,
    getTableAction,
    getDropDownAction,
    registerCustomButtonModal,
    registerEnhanceJsModal,
    registerEnhanceSqlModal,
    registerEnhanceJavaModal,
    registerAuthManagerDrawer,
    registerAuthSetterModal,
    registerCgformModal,
    registerDbToOnlineModal,
    registerCodeGeneratorModal,
  };
}
export { CgformPageType, useCgformList, useCgformIntro };
